﻿using CK.Sprite.Form.Core;
using CK.Sprite.Framework;
using Dapper;
using Dapper.Contrib.Extensions;
using JetBrains.Annotations;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace CK.Sprite.Form.Business
{
    public class StockQtyRepository : IStockQtyRepository
    {
        public StockQtyRepository(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        public IUnitOfWork _unitOfWork { get; private set; }

        public int CheckStockQtyAsync(string stockCode,string itemCode)
        {
            var strSql = $"SELECT COUNT(1) FROM StockQty_t WHERE StockCode = @StockCode AND ItemCode = @ItemCode;";
            return int.Parse(_unitOfWork.Connection.ExecuteScalar(strSql, new { StockCode = stockCode, ItemCode = itemCode }).ToString());
        }
        public async Task AddStockQtyAsync(List<string> fields, JObject addData)
        {
            var dynamicFields = string.Join(",", fields);
            var dynamicFieldValues = string.Join(",@", fields);
            var strSql = $"INSERT INTO StockQty_t(Id,{dynamicFields}) VALUES (@Id,@{dynamicFieldValues});";
            await _unitOfWork.Connection.ExecuteAsync(strSql, addData.ToConventionalDotNetObject());
        }
        public async Task UpdateStockQtyAsync(string stockCode, string itemCode,decimal quantity)
        {
            var strSql = $"UPDATE StockQty_t SET Quantity = Quantity + @Quantity  WHERE StockCode = @StockCode AND ItemCode = @ItemCode;";
            await _unitOfWork.Connection.ExecuteAsync(strSql, new { Quantity = quantity, StockCode = stockCode, ItemCode = itemCode });
        }
    }
}
